package org.an.proj.contacts.net.service.retrofit.coverter;

import com.google.gson.Gson;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by Fcy on 2016/10/11.<br/>
 * responseBodyConverter 和 requestBodyConverter的作用
 */
public class CustomConverterFactory extends Converter.Factory {
  @Override
  public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
    Retrofit retrofit) {
    //		TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    //		return new retrofit2.converter.gson.GsonResponseBodyConverter<>(gson, adapter);
    ResponseConverter<?> responseConverter = new ResponseConverter<>(type);
    return responseConverter;
  }

  /**
   * requestBodyConverter 主要是对应@Body注解,完成对象到RequestBody的构造
   */
  @Override public Converter<?, RequestBody> requestBodyConverter(Type type,
    Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
    //		String string = mGson.toJson(value);
    //		return RequestBody.create(MediaType.parse("application/json; charset=UTF-8"),string);
  }

  public class ResponseConverter<T> implements Converter<ResponseBody, T> {
    Gson gson = new Gson();
    private Type type;

    public ResponseConverter(Type type) {
      this.type = type;
    }

    @Override public T convert(ResponseBody responseBody) throws IOException {
      String result = responseBody.string();
      T t = gson.fromJson(result, type);
      return t;
    }
  }
}


